<template>
  <l-content :app="app" width="1500px" v-loading="loading" no-padding no-breadcrumb>
    <el-form inline label-width="140px" size="mini" ref="form" :rules="rules" :model="form">
      <el-card class="card-bottom-spacing">
        <div slot="header" class="card-title">
          平台信息
        </div>
        <div class="msg-bg-cyan">
          <el-form-item label="状态">
            <span style="display: inline-block;font-size: 20px;" class="font-red font-bold w160">{{status}}</span>
          </el-form-item>
          <el-form-item label="网店退票单号">
            <span style="display: inline-block" class="w160">{{form.prid}}</span>
          </el-form-item>
          <el-form-item label="本地退票单号">
            <span style="display: inline-block" class="w160">{{form.localRefundNo}}</span>
          </el-form-item>
          <el-form-item label="本地订单号" v-if="form.localOrderId">
            <a style="display: inline-block" href="javascript:void(0)" class="w160" @click="onDetail" type="text">{{form.localOrderId}}</a>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="所属网店">
            <el-select class="w160" v-model="form.shopCode">
              <el-option v-for="item in options.shop" :label="item.shopName" :value="item.shopNo" :key="'shopCode' + item.shopNo"/>
            </el-select>
          </el-form-item>
          <el-form-item label="退票类型" prop="refundType">
            <el-select class="w160" v-model="form.refundType" clearable placeholder="请选择">
              <el-option v-for="item in options.platformRefundType" :label="item.value" :value="item.key" :key="'refundType' + item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="网店出票单号" prop="issueBillId">
            <el-input class="w160" v-model="form.issueBillId"/>
          </el-form-item>
          <el-form-item label="提交日期">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.rtTime" class="w200"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="退票事由">
            <el-autocomplete style="width: 1112px;"
                             :fetch-suggestions="(qs, cb) => cb(options.refundDesc)"
                             v-model="form.refundDesc"/>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="card-bottom-spacing">
        <div slot="header" class="card-title">
          旅客信息
          <el-button type="primary" @click="onAddPassenger" size="mini" style="margin-left: 10px"><i class="fa fa-plus"></i> 新增旅客</el-button>
        </div>
        <el-table
          show-summary
          :summary-method="tableSummary"
          class="el-easy-ui-table"
          border
          :data="form.items">
          <el-table-column label="序号" width="50" type="index">
          </el-table-column>
          <el-table-column
            label="出发"
            min-width="50">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.dPort" @input="v => $nextTick(() => {
                  scope.row.dPort = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="到达"
            min-width="50">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.aPort" @input="v => $nextTick(() => {
                  scope.row.aPort = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="flight"
            label="航班"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.flight" @input="v => $nextTick(() => {
                  scope.row.flight = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="subClass"
            label="舱位"
            min-width="50">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.subClass" @input="v => $nextTick(() => {
                  scope.row.subClass = v.toUpperCase()
                })"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="乘机日期"
            min-width="160">
            <template slot-scope="scope">
              <el-form-item>
                <el-date-picker type="datetime" v-model="scope.row.takeOffTime"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="passengerName"
            label="姓名"
            min-width="100">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.passengerName"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="票号" min-width="120">
            <template slot-scope="scope">
              <el-form-item>
                <el-input placeholder="xxx-xxxxxxxxxx" v-model="scope.row.ticketNoAll"
                          @input="onInputTicketNoAll(scope.row, $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="printPrice"
            label="票面价"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.printPrice" @input="onPassengerInput(scope.$index, 'printPrice', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="cost"
            label="销售价"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.cost" @input="onPassengerInput(scope.$index, 'cost', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="税费+燃油"
            min-width="100">
            <template slot-scope="scope">
              <el-form-item style="display: inline-table">
                <el-input style="display: table-cell;width: 50%;" v-model="scope.row.tax"
                          @input="onPassengerInput(scope.$index, 'tax', $event)"/>
                <el-input style="display: table-cell;width: 50%;" v-model="scope.row.oilFee"
                          @input="onPassengerInput(scope.$index, 'oilFee', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="refundFee"
            label="平台退票费"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-input v-model="scope.row.refundFee" @input="onPassengerInput(scope.$index, 'refundFee', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="payFlightAgency"
            label="平台退款"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item
                :prop="'items[' + scope.$index + '].payFlightAgency'"
                :rules="rules.payFlightAgency">
                <el-input v-model="scope.row.payFlightAgency"
                          @input="onPassengerInput(scope.$index, 'payFlightAgency', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="airlineRefund"
            label="航司退款"
            min-width="80">
            <template slot-scope="scope">
              <el-form-item
                :prop="'items[' + scope.$index + '].airlineRefund'"
                :rules="rules.airlineRefund">
                <el-input v-model="scope.row.airlineRefund"
                          @input="onPassengerInput(scope.$index, 'airlineRefund', $event)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="利润"
            min-width="80">
            <template slot-scope="scope">
              {{((scope.row.airlineRefund !== '' && scope.row.airlineRefund !== null) ? ((+(scope.row.airlineRefund||0)) - (+(scope.row.payFlightAgency||0))) : 0) |
              money}}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="80">
            <template slot-scope="scope">
              <c-pop-button type="danger" size="mini" p-msg="确认删除？"
                            @click="$event => {form.items.splice(scope.$index ,1);$event.isLoading(false)}"><i class="fa fa-trash"></i> 删除
              </c-pop-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="card-bottom-spacing">
        <div slot="header" class="card-title">
          航司退票信息
        </div>
        <div>
          <el-form-item label="出票渠道" prop="issueChannel">
            <el-select class="w200" v-model="form.issueChannel" clearable placeholder="请选择">
              <el-option v-for="item in options.issueChannel" :label="item.value" :value="item.key" :key="'issueChannel' + item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="退票类型" prop="airlineRefundType">
            <el-select class="w200" v-model="form.airlineRefundType" clearable placeholder="请选择">
              <el-option v-for="item in options.refundType" :label="item.value" :value="item.key" :key="'airlineRefundType' + item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="支付方式" prop="payAccountType">
            <el-select class="w200" v-model="form.payAccountType" filterable>
              <el-option v-for="item in options.payAccountType" :label="item.value" :value="item.key" :key="'payType' + item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="支付流水" prop="payNo">
            <el-input class="w200" v-model="form.payNo"/>
          </el-form-item>
        </div>
        <div v-if="['BOP', 'BSP', 'B2B'].indexOf(form.issueChannel) > -1">
          <el-form-item label="小编码" prop="pnr" class="input-no-padding" :rules="pnrRule">
            <div class="w200">
              <el-input v-model="form.pnr" :class="{'w100': canX}"/>
              <easy-button v-if="canX" type="warning" @click="onCancelPnr($event)">取消PNR</easy-button>
            </div>
          </el-form-item>
          <el-form-item label="大编码" prop="airlinePnr" class="input-no-padding">
            <el-input class="w200" v-model="form.airlinePnr" placeholder="   需自动B2B退票就填写"/>
          </el-form-item>
          <el-form-item label="预定Office号" prop="officeNo" :rules="pnrRule">
            <el-input class="w200" v-model="form.officeNo"/>
          </el-form-item>
          <el-form-item label="出票Office号" prop="issueOfficeNo" :rules="pnrRule">
            <el-select v-model="form.issueOfficeNo" class="w200" clearable>
              <el-option v-for="item in options.etermGroup" :key="'issueOfficeNo' + item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="最晚取消PNR时间" prop="latestCancelPnrTime">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.latestCancelPnrTime" class="w200"/>
          </el-form-item>
          <el-form-item label="航司订单号" >
            <el-input  v-model="form.airlineOrderId" placeholder="需自动B2B退票就填写" class="w200"/>
          </el-form-item>
          <el-form-item label="提交航司退票日期">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.submitRefundTime" class="w200"/>
          </el-form-item>
          <el-form-item label="航司退款日期">
            <el-date-picker format="yyyy-MM-dd HH:mm" type="datetime" v-model="form.refundTime" class="w200"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="备注">
            <el-input
              v-model="form.remarks"
              type="textarea"
              style="width: 1250px;"
              :autosize="{ minRows: 2, maxRows: 8}"/>
          </el-form-item>
        </div>
      </el-card>
    </el-form>

    <el-card class="card-bottom-spacing">
      <div style="text-align: center">
        <easy-button v-if="canConfirm" type="primary" class="w120" @click="onConfirm">确认退票</easy-button>
        <el-button v-if="canReject" type="primary" class="w120" @click="onReject">拒绝退票</el-button>
        <easy-button v-if="canToSubmitAirline" type="primary" class="w120" @click="onChangeStatus($event, '1')">待提交退票</easy-button>
        <easy-button v-if="canSubmitAirLine && form.issueChannel === 'B2B' && form.airlineOrderId && form.airlinePnr"
                     tip="请填写大编码和航司订单号"
                     type="primary"
                     class="w120"
                     @click="onAutoRefund">B2B自动退票</easy-button>
        <easy-button v-if="canSubmitAirLine" type="primary" class="w120" @click="onSubmitToAirline">已提交航司</easy-button>
        <easy-button v-if="canAuditAirLine" type="primary" class="w120" @click="onChangeStatus($event, '3')">航司已审核</easy-button>
        <easy-button v-if="canRefundAirLine" type="primary" class="w120" @click="onChangeStatus($event, '4')">航司已退款</easy-button>
        <easy-button v-if="canSave" type="warning" class="w120" @click="onSave">保存</easy-button>
        <easy-button v-if="canDelete" type="danger" class="w120" @click="onDelete">删除</easy-button>
        <el-button class="w120" @click="onClose">关闭</el-button>
      </div>
    </el-card>

    <el-collapse class="easy-ui-collapse">
      <el-collapse-item>
        <div slot="title" class="card-title">
          操作日志
        </div>
        <el-table
          :data="orderLog"
          border
          class="el-easy-ui-table">
          <el-table-column
            label="序号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            label="操作时间"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.operateTime | datetimeFormat}}
            </template>
          </el-table-column>
          <el-table-column
            prop="operator"
            label="操作人"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="actionType"
            label="动作"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="actionMsg"
            label="备注"
            min-width="300">
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <el-dialog
      width="400px"
      :visible.sync="rejectDialog.visible"
      title="确认拒绝？">
      <el-form size="mini" label-width="70px">
        <el-form-item label="拒绝原因">
          <el-select v-model="rejectDialog.form.rejectType" style="width: 100%">
            <el-option v-for="item in options.rejectType" :label="item.value" :value="item.key" :key="'rejectType' + item.key"/>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialog.visible = false">取 消</el-button>
        <easy-button type="primary" @click="onRejectDialogOk">确 定</easy-button>
      </span>
    </el-dialog>

  </l-content>
</template>

<script>
import Tab from '@/classes/Tab'
import tabManager from '@/eventBus/tabManager'

export default {
  name: 'OrderRefundDetail',
  props: {
    app: {
      type: Object,
      default () {
        return {
          extra: {
            refundId: ''
          }
        }
      }
    }
  },
  data () {
    return {
      now: new Date(),
      loading: false,
      options: {
        refundDesc: [],
        etermGroup: [],
        issueChannel: [],
        shop: [],
        refundType: [],
        rejectType: [],
        payAccountType: []
      },
      orderLog: [],
      form: {
        id: null,
        airlineOrderId: null,
        shopCode: null,
        orderId: null,
        localRefundNo: null,
        prid: null,
        feeType: null,
        isForceAudited: null,
        refundServerFee: null,
        currency: null,
        conversionRate: null,
        createTime: null,
        isConfirm: null,
        audited: null,
        rtOper: null,
        rtTime: null,
        flightClass: null,
        prepayType: null,
        tickets: null,
        refundDesc: null,
        isRefund: null,
        takeOffTime: null,
        row: null,
        countNumber: null,
        urgency: null,
        refundReason: null,
        status: null,
        latestCancelPnrTime: null,
        cancelPnrTime: null,
        updateTime: null,
        updateUser: null,
        platform: null,
        issueBillId: null,
        issueChannel: null,
        pnr: null,
        airlinePnr: null,
        payType: null,
        payAccountType: null,
        payNo: null,
        officeNo: null,
        issueOfficeNo: null,
        refundTime: null,
        submitRefundTime: null,
        submitUser: null,
        airlineRefundType: null,
        refundType: null,
        remarks: null,
        localOrderId: null,
        cancelPnr: false,
        items: []
      },
      rules: {
        shopCode: this.$checkRules.orderRefundDetail.shopCode,
        refundType: this.$checkRules.orderRefundDetail.refundType,
        payFlightAgency: this.$checkRules.orderRefundDetail.payFlightAgency,
        airlineRefund: [],
        issueChannel: this.$checkRules.orderRefundDetail.issueChannel,
        latestCancelPnrTime: this.$checkRules.orderRefundDetail.latestCancelPnrTime,
        issueBillId: this.$checkRules.notEmpty,
        airlineRefundType: [],
        payAccountType: [],
        payNo: []
      },
      rejectDialog: {
        visible: false,
        form: {
          refundId: this.app.extra.refundId,
          rejectType: ''
        }
      }
    }
  },
  watch: {
    'form.issueChannel' () {
      this.$refs['form'].clearValidate(['pnr'])
    },
    'form.status' (v) {
      this.rules.airlineRefund = []
      this.rules.airlineRefundType = []
      this.rules.payAccountType = []
      this.rules.payNo = []
      // 航司退款校验
      if (v === 'TO_AIRLINE_AUDIT') {
        this.rules.airlineRefund = this.$checkRules.orderRefundDetail.airlineRefund
      } else if (v === 'TO_SUBMIT_AIRLINE') {
        this.rules.airlineRefundType = this.$checkRules.notEmpty
        this.rules.payAccountType = this.$checkRules.notEmpty
        this.rules.payNo = this.$checkRules.notEmpty
      }
    }
  },
  computed: {
    pnrRule () {
      if (['B2B', 'BSP', 'BOP'].indexOf(this.form.issueChannel) > -1) {
        return this.$checkRules.orderRefundDetail.pnr
      } else {
        return []
      }
    },
    status () {
      const map = {
        TO_CONFIRM: '待确认',
        REJECTED: '已拒绝',
        CONFIRMED: '等待取消PNR',
        TO_HANDLE: '待人工处理',
        X_PNR_FAILED: '取消PNR失败',
        TO_SUBMIT_AIRLINE: '待提交退票',
        TO_AIRLINE_AUDIT: '待航司审核',
        TO_AIRLINE_REFUND: '待航司退款',
        AIRLINE_REFUNDED: '退票完成'
      }
      return map[this.form.status] || ''
    },
    canConfirm () {
      return this.form.status === 'TO_CONFIRM'
    },
    canReject () {
      return this.form.status === 'TO_CONFIRM'
    },
    canX () {
      return (this.form.status === 'CONFIRMED' || this.form.status === 'TO_HANDLE') && (['B2B', 'BSP', 'BOP'].indexOf(this.form.issueChannel) > -1)
    },
    canToSubmitAirline () {
      return this.form.status === 'CONFIRMED' || this.form.status === 'TO_HANDLE'
    },
    canSubmitAirLine () {
      return this.form.status === 'TO_SUBMIT_AIRLINE'
    },
    canAuditAirLine () {
      return this.form.status === 'TO_AIRLINE_AUDIT'
    },
    canRefundAirLine () {
      return this.form.status === 'TO_AIRLINE_REFUND'
    },
    canSave () {
      return this.form.status !== 'REJECTED'
    },
    canDelete () {
      return this.form.status === 'TO_CONFIRM' || this.form.status === 'CONFIRMED' || this.form.status === 'TO_HANDLE' || this.form.status === 'TO_SUBMIT_AIRLINE'
    }
  },
  created () {
    this.$dateUtils.getNow().then(now => {
      this.now = now
    })
    this.refresh()
    this.loadOptions()
  },
  methods: {
    tableSummary (param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '汇总'
          return
        }
        if ((index >= 8 && index <= 13) && index !== 10) {
          const values = data.map(item => Number(item[column.property] || 0))
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
        } else if (index === 10) {
          const values1 = data.map(item => Number(item.tax || 0))
          const values2 = data.map(item => Number(item.oilFee || 0))
          const sum = [...values1, ...values2].reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
        } else if (index === 14) {
          // 航司退款
          const values1 = data.map(item => Number(item.airlineRefund || 0))
          // 平台退款
          const values2 = data.map(item => -Number(((item.airlineRefund === null || item.airlineRefund === '' || item.airlineRefund === undefined) ? 0 : item.payFlightAgency) || 0))
          const sum = [...values1, ...values2].reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = this.$options.filters.money(sum)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    refresh () {
      this.loadDetail()
      this.loadOrderLog()
    },
    loadOptions () {
      this.$service.options.getIssueChannel().then(res => {
        this.options.issueChannel = res.data
      })
      this.$service.order.queryAirOnlineShopList().then(res => {
        this.options.shop = res.data
      })
      this.$service.options.getRefundType().then(res => {
        this.options.refundType = res.data
      })
      this.$service.options.getRejectType().then(res => {
        this.options.rejectType = res.data
        if (res.data.length > 0) {
          this.rejectDialog.form.rejectType = res.data[0].key
        }
      })
      // this.$service.options.getPayType().then(res => {
      //   this.options.payType = res.data
      // })
      this.$service.options.getYeePayAccountType().then(res => {
        this.options.payAccountType = res.data
      })
      this.$service.eterm.queryAllGroupList().then(res => {
        this.options.etermGroup = res.data
      })
      this.options.platformRefundType = [
        {'key': '自愿', 'value': '自愿'},
        {'key': '非自愿', 'value': '非自愿'}
      ]
      this.$service.options.getRefundDesc().then(res => {
        this.options.refundDesc = res.data
      })
    },
    loadDetail () {
      this.loading = true
      this.$service.airRefund.detail({refundId: this.app.extra.refundId}).then(res => {
        Object.assign(this.form, res.data)
        if (this.form.rtTime) {
          this.form.rtTime = new Date(this.form.rtTime)
        }
        if (this.form.latestCancelPnrTime) {
          this.form.latestCancelPnrTime = new Date(this.form.latestCancelPnrTime)
        }
        if (this.form.submitRefundTime) {
          this.form.submitRefundTime = new Date(this.form.submitRefundTime)
        }
        if (this.form.refundTime) {
          this.form.refundTime = new Date(this.form.refundTime)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    onConfirm (done) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let tip = '是否确认退票？'
          const latestCancelPnrTime = new Date(this.form.latestCancelPnrTime)
          const remaining = Math.round((latestCancelPnrTime.getTime() - this.now.getTime()) / 1000 / 60)
          if (remaining < 0) {
            tip = '设置的最晚取消pnr时间小于当前时间，请确认是否确认退票？'
          } else if (remaining <= 15) {
            tip = '设置的最晚取消pnr时间离现在只差' + remaining + '分钟了，请确认是否确认退票？'
          }
          this.$confirm(tip, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$service.airRefund.confirm(this.form).then(res => {
              this.refresh()
            }).finally(done)
          }).catch(done)
        } else {
          this.$alert('校验未通过', '提示')
          done()
        }
      })
    },
    onAutoRefund (done) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$confirm('是否确认自动提交航司退票？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // this.form.status = 'TO_AIRLINE_AUDIT'
            this.$service.airRefund.autoRefund(this.form).then(res => {
              this.refresh()
            }).finally(done)
          }).catch(done)
        } else {
          this.$alert('校验未通过', '提示')
          done()
        }
      })
    },
    onSubmitToAirline (done) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$confirm('是否确认已提交航司？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.form.status = 'TO_AIRLINE_AUDIT'
            this.$service.airRefund.submitToAirline(this.form).then(res => {
              this.refresh()
            }).finally(done)
          }).catch(done)
        } else {
          this.$alert('校验未通过', '提示')
          done()
        }
      })
    },
    onReject () {
      this.rejectDialog.visible = true
    },
    onRejectDialogOk (done) {
      this.$service.airRefund.reject(this.rejectDialog.form).then(res => {
        this.rejectDialog.visible = false
        this.refresh()
      }).finally(done)
    },
    onChangeStatus (done, key) {
      this.$refs['form'].validate(valid => {
        const map = {
          '1': {desc: '待提交退票', status: 'TO_SUBMIT_AIRLINE'},
          '2': {desc: '已提交航司', status: 'TO_AIRLINE_AUDIT'},
          '3': {desc: '航司已审核', status: 'TO_AIRLINE_REFUND'},
          '4': {desc: '航司已退款', status: 'AIRLINE_REFUNDED'}
        }
        const item = map[key]

        if (valid) {
          this.$confirm('是否修改状态为[' + item.desc + ']？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$service.airRefund.changeStatus(Object.assign({}, this.form, {status: item.status})).then(res => {
              this.refresh()
            }).finally(done)
          }).catch(done)
        } else {
          this.$alert('校验未通过', '提示')
          done()
        }
      })
    },
    onCancelPnr (done) {
      this.$confirm('是否取消PNR？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.airRefund.changeStatus(Object.assign({}, this.form, {status: 'TO_SUBMIT_AIRLINE', cancelPnr: true})).then(res => {
          this.refresh()
        }).finally(done)
      }).catch(done)
    },
    onSave (done) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$service.airRefund.save(this.form).then(res => {
            this.refresh()
          }).finally(done)
        } else {
          this.$alert('校验未通过', '提示')
          done()
        }
      })
    },
    onDelete (done) {
      this.$confirm('是否删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$service.airRefund.delete({id: this.form.id}).then(res => {
          this.app.close()
          // 打开退票单列表页面等价于刷新页面
          tabManager.addTab(new Tab({key: 'airOrderManage.refundOrderList'}))
        }).finally(done)
      }).catch(done)
    },
    onClose () {
      this.app.close()
    },
    onAddPassenger () {
      if (this.form.items.length > 0) {
        var item0 = Object.assign({}, this.form.items[0])
        item0.passengerName = null
        item0.ticketNoAll = null
        item0.id = null
        this.form.items.push(item0)
      } else {
        this.form.items.push({
          dPort: null,
          aPort: null,
          flight: null,
          subClass: null,
          takeOffTime: null,
          passengerName: null,
          ticketNoAll: null,
          printPrice: null,
          cost: null,
          tax: 50,
          oilFee: 30,
          refundFee: null,
          payFlightAgency: null,
          airlineRefundFee: null,
          airlineRefund: null
        })
      }
    },
    loadOrderLog () {
      this.$service.airRefund.getLogs({refundId: this.app.extra.refundId}).then(res => {
        this.orderLog = res.data
      })
    },
    onDetail () {
      window.open('#/air-order-manage/order-issue-detail?localOrderId=' + this.form.localOrderId)
    },
    calcCost (idx, key, v) {
      if (v !== null && v !== '') {
        const item = this.form.items[idx]
        const total = Number(item.cost || 0) + Number(item.tax || 0) + Number(item.oilFee || 0)
        if (key === 'payFlightAgency') {
          item.refundFee = '' + Number((total - Number(v)).toFixed(2))
        } else if (key === 'refundFee') {
          item.payFlightAgency = '' + Number((total - Number(v)).toFixed(2))
        }
      }
    },
    onPassengerInput (idx, key, v) {
      if (idx === 0) {
        this.$nextTick(() => {
          this.form.items.forEach((item, index) => {
            item[key] = v
            this.calcCost(index, key, v)
          })
        })
      } else {
        this.calcCost(idx, key, v)
      }
    },
    onInputTicketNoAll (row, v) {
      const str = v.replace(/-/g, '')
      if (str.length > 3) {
        const no1 = str.substring(0, 3)
        const no2 = str.substring(3)
        this.$nextTick(() => {
          row.ticketNoAll = no1 + '-' + no2
        })
      }
    }
  }
}
</script>

<style></style>
